<?php

namespace app\api\service;

use app\lib\exception\PayException;
use app\common\Helper;
use app\admin\model\User;
use app\admin\model\Advertise;

use think\Loader;
use think\Log;

Loader::import('WxPay.WxPay',EXTEND_PATH,'.Api.php');

class Adpay
{
    private $userId;
    private $advertiseId;
    private $storeId;

    function __construct($param)
    {
        $this->advertiseId = $param['advertiseId'];
        $this->userId = $param['userId'];
    }

    public function pay(){
        $advertise = Advertise::get($this->advertiseId);
        if(!$advertise){
            return show(config('status.ERROR_STATUS'),'该广告订单不存在','该广告订单不存在');
        }

        return show(config('status.SUCCESS_STATUS'),'ok',$this->makeWxPreOrder($advertise->advertiseCost,$advertise->advertiseTitle));
    }

    /**
     * 生成微信预订单
     * @param $totalPrice
     * @return array
     */
    private function makeWxPreOrder($totalPrice,$productName){
        $openid = User::getopenId($this->userId);
        $wxOrderData = new \WxPayUnifiedOrder();
        $wxOrderData->SetOut_trade_no($this->advertiseId);
        $wxOrderData->SetTrade_type('JSAPI');
        $wxOrderData->SetTotal_fee($totalPrice);
        $wxOrderData->SetBody($productName);
        $wxOrderData->SetOpenid($openid);
        $wxOrderData->SetNotify_url(config('wx.adpay_back_url'));

        return $this->getPaySignature($wxOrderData);
    }

    /**
     * 请求微信统一下单接口返回给客户端一组支付参数
     * @param $wxOrderData
     * @return \成功时返回，其他抛异常
     */
    private function getPaySignature($wxOrderData){
        $wxOrder = \WxPayApi::unifiedOrder($wxOrderData);
        if($wxOrder['return_code'] != 'SUCCESS' || $wxOrder['result_code'] != 'SUCCESS'){
            Log::record($wxOrder,'error');
            Log::record('获取预支付订单失败','error');
        }
        if($wxOrder['return_code'] == 'FAIL'){
            throw new PayException([
                'msg' => '商户号或者支付秘钥异常'
            ]);
        }
        $this->recordPreOrder($wxOrder);

        return $this->sign($wxOrder);
    }

    /**
     * 生成签名
     * @param $wxOrder
     * @return array
     */
    private function sign($wxOrder){
        $jsApiPayData = new \WxPayJsApiPay();
        $jsApiPayData->SetAppid(config('wx.app_id'));
        $jsApiPayData->SetTimeStamp((string)time());
        $jsApiPayData->SetNonceStr(Helper::getUUID());
        $jsApiPayData->SetPackage('prepay_id='.$wxOrder['prepay_id']);
        $jsApiPayData->SetSignType('md5');
        $sign = $jsApiPayData->MakeSign();
        $rowValues = $jsApiPayData->GetValues();
        $rowValues['paySign'] = $sign;
        unset($rowValues['appId']);

        return $rowValues;
    }

    private function recordPreOrder($wxOrder){
        Advertise::where('id','=',$this->advertiseId)->update(['prepay_id'=>$wxOrder['prepay_id']]);
    }
}